package com.colin.juc.flowcontrol.condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by Colin on 2020/5/31 12:41
 * email: colinzhaodong@gmail.com
 * desc: 演示Condition
 *
 * @author zhaod
 */
public class ConditionDemo1 {
	private static final ReentrantLock LOCK = new ReentrantLock();
	private static final Condition CONDITION = LOCK.newCondition();

	private void method1() throws InterruptedException {
		LOCK.lock();
		try {
			System.out.println("条件不满足,开始await");
			CONDITION.await();
			System.out.println("条件满足了,开始执行后续的任务");
		}finally {
			LOCK.unlock();
		}
	}

	private void method2() {
		LOCK.lock();
		try{
			System.out.println("准备工作完成，唤醒其他的线程");
			CONDITION.signal();
		}finally {
			LOCK.unlock();
		}
	}

	public static void main(String[] args) throws InterruptedException {
		ConditionDemo1 conditionDemo1 = new ConditionDemo1();
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Thread.sleep(1000);
					conditionDemo1.method2();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}).start();
		conditionDemo1.method1();
	}
}
